import React, { useEffect, useState } from 'react';
import { getLoadMapList, getTenantID, getSelectDataMapList, splitFileUrl, downloadTemplate, getFileNameNotType, removeDateHmsStr } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import { useDescriptionsType } from '@/components/DescriptionsType';
import { RegularExpression } from '@/common/constVariable';
import { Form, Select, Tooltip, TreeSelect, message, Button } from 'antd';
import { UploadFormCommon } from '@/components/UploadForm';
import MyIcon from '@/components/MyIcon';
import { UpdateMaterielView } from './UpdateMaterielView';
import { TagSelectNew as TagSelect } from '@/components/TagSelectNew';
import moment from 'moment';
import { getBaseUrl } from '@/services/urlconst';
import { readReadShowFileService } from '@/services/BaseLayout';
import { EyeOutlined } from '@ant-design/icons';

const repealTypeList = [
  { name: '正常报废', value: '0' },
  { name: '非正常报废', value: '1' },
];

const damageTypeList = [
  { name: '待核查', value: '0' },
  { name: '人力因素', value: '1' },
  { name: '自然因素', value: '2' },
];

const riskLevelList = [
  { name: '暂无风险', value: '0' },
  { name: '低风险', value: '1' },
  { name: '中风险', value: '2' },
  { name: '高风险', value: '3' },
];

const claimTypeList = [
  { name: '无索赔', value: '0' },
  { name: '个人承担', value: '1' },
  { name: '部门承担', value: '2' },
];

const getUpdateConfig = ({ pageType, record, handleMaterialModal, formName }) => {
  const [isRequireReson, setIsRequireReson] = useState<boolean>(false);
  // 年限到期
  const [isMaturity, setIsMaturity] = useState<boolean>(true);

  /** 轻阅读预览 */
  const { readReadShowFileRun } = readReadShowFileService();

  /**轻阅读预览 */
  const onOpenReadOfdWord = (fieldUrl: string) => {
    readReadShowFileRun({ fieldPath: `${getBaseUrl()}${fieldUrl}` });
  };

  /** 切换表单 */
  useEffect(() => {
    // 回填表单
    formName?.setFieldsValue({
      ...record,
      createTime: moment(record?.createTime),
    });
    if (pageType !== 'add') {
      if (record?.repealType === '0') {
        setIsMaturity(true);
      } else {
        setIsMaturity(false);
      }
    }
  }, []);

  const disabled: boolean = pageType === 'detail';

  /** 表单配置 */
  const [config, methods] = useDescriptionsType({
    labelWidth: 190,
    basicForm: formName,
    name: 'accept-addAndEdit',
    schemas: [
      {
        key: 'accept-basic',
        title: '',
        fieldChildren: [
          {
            label: '申请日期',
            field: 'createTime',
            component: 'DatePicker',
            placeholder: '请选择申请日期',
            disabled: disabled,
            required: true,
            disabledDate: (current) => {
              return current && current > moment(new Date(), 'YYYY-MM-DD');
            },
          },
          {
            field: `applyCode`,
            label: `流水单号`,
            component: 'Input',
            disabled: false,
            placeholder: '自动带出',
            required: false,
          },
          {
            field: `createrName`,
            label: `申请人`,
            component: 'Input',
            disabled: true,
            required: false,
            placeholder: '自动带出',
          },
          {
            field: `createPhone`,
            label: `联系电话`,
            component: 'Input',
            disabled: true,
            required: false,
            placeholder: '自动带出',
          },
          {
            field: `createDepartmentName`,
            label: `申请部门/单位`,
            component: 'Input',
            disabled: true,
            required: false,
            placeholder: '自动带出',
          },
          {
            field: `createPositionName`,
            label: `职务岗位`,
            component: 'Input',
            disabled: true,
            required: false,
            placeholder: '自动带出',
          },
          {
            field: `applyTitle`,
            label: `事项名称`,
            component: 'Input',
            disabled: disabled,
            placeholder: '请输入',
            required: true,
            autoComplete: 'off',
            colSpan: 0,
          },
          {
            field: 'repealType',
            label: `报废类别`,
            required: true,
            component: 'Render',
            disabled: disabled,
            placeholder: '请选择',
            colSpan: 2,
            render: (text) => {
              if (pageType === 'detail') {
                return <span>{repealTypeList.find((item) => item.value == text)?.name || '--'}</span>;
              } else {
                return (
                  <TagSelect
                    colSpan={24}
                    formLabel={''}
                    formName={'repealType'}
                    defalultKeys={Number(text)}
                    onChange={(value) => {
                      if (value == '0') {
                        setIsMaturity(true);
                      } else {
                        setIsMaturity(false);
                      }
                    }}
                    // radioDisabled={}
                    radioList={repealTypeList}
                  />
                  // <Select
                  //   onChange={(_value, node) => { }}
                  //   options={repealTypeList}
                  //   loading={false}
                  //   disabled={disabled}
                  //   placeholder="请选择"
                  //   fieldNames={{
                  //     label: 'label',
                  //     value: 'value',
                  //   }}
                  //   showSearch={true}
                  // />
                );
              }
            },
          },
          {
            field: `damageType`,
            label: `损坏类型`,
            required: true,
            component: 'Render',
            disabled: disabled,
            placeholder: '请选择',
            ishidden: isMaturity,
            render: (text) => {
              if (pageType === 'detail') {
                return <span>{damageTypeList.find((item) => item.value == text)?.name || '--'}</span>;
              } else {
                return (
                  <TagSelect
                    colSpan={24}
                    formLabel={''}
                    formName={'damageType'}
                    defalultKeys={Number(text)}
                    onChange={(value) => {}}
                    // radioDisabled={}
                    radioList={damageTypeList}
                  />
                  // <Select
                  //   onChange={(_value, node) => { }}
                  //   options={damageTypeList}
                  //   loading={false}
                  //   disabled={disabled}
                  //   placeholder="请选择"
                  //   fieldNames={{
                  //     label: 'name',
                  //     value: 'value',
                  //   }}
                  //   showSearch={true}
                  // />
                );
              }
            },
          },
          {
            field: `riskLevel`,
            label: `风险程度`,
            required: true,
            component: 'Render',
            disabled: disabled,
            placeholder: '请选择',
            colSpan: isMaturity ? 2 : 1,
            render: (text) => {
              if (pageType === 'detail') {
                return <span>{riskLevelList.find((item) => item.value == text)?.name || '--'}</span>;
              } else {
                return (
                  <Select
                    onChange={(_value, node) => {}}
                    options={riskLevelList}
                    loading={false}
                    disabled={disabled}
                    placeholder="请选择"
                    fieldNames={{
                      label: 'name',
                      value: 'value',
                    }}
                    showSearch={true}
                  />
                );
              }
            },
          },
          {
            field: `claimType`,
            label: `索赔类型`,
            required: true,
            colSpan: 2,
            component: 'Render',
            disabled: disabled,
            placeholder: '请选择',
            ishidden: isMaturity,
            render: (text) => {
              if (pageType === 'detail') {
                return <span>{claimTypeList.find((item) => item.value == text)?.name || '--'}</span>;
              } else {
                return (
                  <TagSelect
                    colSpan={24}
                    formLabel={''}
                    formName={'claimType'}
                    defalultKeys={Number(text)}
                    onChange={(_value) => {
                      if (_value == 0) {
                        setIsRequireReson(false);
                      } else {
                        setIsRequireReson(true);
                      }
                    }}
                    // radioDisabled={}
                    radioList={claimTypeList}
                  />
                  // <Select
                  //   onChange={(_value, node) => {
                  //     if (_value == 0) {
                  //       setIsRequireReson(false);
                  //     } else {
                  //       setIsRequireReson(true);
                  //     }
                  //   }}
                  //   options={claimTypeList}
                  //   loading={false}
                  //   disabled={disabled}
                  //   placeholder="请选择"
                  //   fieldNames={{
                  //     label: 'name',
                  //     value: 'value',
                  //   }}
                  //   showSearch={true}
                  // />
                );
              }
            },
          },
          {
            field: `claimReason`,
            label: `索赔原因`,
            component: 'InputTextArea',
            disabled: disabled,
            placeholder: '请填写',
            required: isRequireReson,
            ishidden: isMaturity || !isRequireReson,
            colSpan: 2,
            allowClear: true,
            showCount: true,
            maxLength: 200,
            autoSize: { minRows: 2, maxRows: 4 },
          },
          {
            field: `applyInfo`,
            label: `申请理由`,
            component: 'InputTextArea',
            disabled: disabled,
            placeholder: '请填写',
            required: true,
            colSpan: 2,
            allowClear: true,
            showCount: true,
            maxLength: 200,
            autoSize: { minRows: 2, maxRows: 4 },
          },
          {
            field: `applyFile`,
            label: `相关附件`,
            component: 'Render',
            required: false,
            placeholder: '请上传',
            render: (text, record) => {
              const fileName = 'applyFile';
              return (
                <>
                  {!disabled ? (
                    <UploadFormCommon
                      form={formName}
                      fileFormName={fileName}
                      spanCol={24}
                      inRowProportion={24}
                      name={'attachFile'}
                      required={false}
                      // accept={'.doc|.docx'}
                      url={'/assetInfo/uploadFile'}
                      downloadUrl={'/assetInfo/downloadFile'}
                      fileFormDelName={'delFile'}
                      delFunc={(delFilePath: string) => {
                        console.log('--- w文件url', delFilePath);
                      }}
                      // maxFile={1}
                      defaultFiles={text}
                      hintTitle={'且只能上传 1 个！'}
                      fieldBusiPath={'assetFile'}
                      // isShowUploadBtn={true}
                    >
                      上传
                    </UploadFormCommon>
                  ) : (
                    <div
                      style={{
                        height: '100%',
                        display: 'flex',
                        alignItems: 'center',
                        marginLeft: '8px',
                      }}
                    >
                      {record?.[fileName]
                        ? splitFileUrl(record?.[fileName])?.map((e, i) => {
                            return (
                              <div>
                                <Tooltip title={e.attachName} key={new Date().getTime() * 25615265152 + e?.attachName}>
                                  <a
                                    onClick={() => {
                                      message.success('下载中，请稍后...');
                                      downloadTemplate('/assetInfo/downloadFile', e?.attachName, e?.attachUrl, () => {});
                                    }}
                                  >
                                    <MyIcon type="icon-file-text-fill" />
                                    &nbsp;
                                    {getFileNameNotType(e.attachName, 8)}
                                  </a>
                                </Tooltip>
                                {/* 轻阅读预览 */}
                                <Tooltip title={'在线预览'}>
                                  <Button type="link" size="small" onClick={() => onOpenReadOfdWord(e?.attachUrl)} icon={<EyeOutlined />} />
                                </Tooltip>
                              </div>
                            );
                          })
                        : '--'}
                    </div>
                  )}
                </>
              );
            },
          },
        ],
      },
      {
        key: 'accept-procurement',
        title: '',
        fieldCustomDom: <UpdateMaterielView handleMaterialModal={handleMaterialModal} pageType={pageType} />,
      },
    ],
  });

  return {
    config,
    methods,
  };
};

export { getUpdateConfig, repealTypeList, damageTypeList, riskLevelList, claimTypeList };
